package com.lvneng.processor;

import com.google.common.collect.Maps;
import com.lvneng.core.ModbusConsoleApp;

import java.util.HashMap;
import java.util.Map;

public class DataMap {
    private static Map<String,Integer[]> map = Maps.newConcurrentMap();
    public static void update(int slaveId,int functionCode,int startingAddress,Integer value){
        String identifier = slaveId + "-" + functionCode;
        Integer[] array = map.get(identifier);
        if(array == null){
            array = new Integer[ModbusConsoleApp.maximumAddressLen];
            for(int i=0;i<ModbusConsoleApp.maximumAddressLen;i++){
                array[i] = 0;
            }
            map.put(identifier,array);
        }
        if(startingAddress >= 0 && startingAddress < ModbusConsoleApp.maximumAddressLen){
            array[startingAddress] = value;
        }
    }

    public static Integer getValue(int slaveId,int functionCode,int startingAddress){
        String identifier = slaveId + "-" + functionCode;
        Integer[] array = map.get(identifier);
        if(array != null && startingAddress < ModbusConsoleApp.maximumAddressLen){
            return array[startingAddress];
        }
        return 0;
    }

    public static Integer[] getBatchValue(int slaveId,int functionCode,int startingAddress,int quantity){
        Integer[] returnArray = new Integer[quantity];
        for(int i=0;i<quantity;i++){
            returnArray[i] = 0;
        }
        String identifier = slaveId + "-" + functionCode;
        Integer[] array = map.get(identifier);
        if(array != null && startingAddress < ModbusConsoleApp.maximumAddressLen && quantity < ModbusConsoleApp.maximumAddressLen){
            for(int i=0;i<quantity;i++){
                Integer d = array[startingAddress + i];
                returnArray[i] = d;
            }
            return returnArray;
        }
        return returnArray;
    }
}
